package com.pan.structual.composite.node;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class XmlNode {
    String name;
    String value;{

    }

    List<XmlNode> childList;{
        childList = new ArrayList<>();
    }

//    先不要考虑属性
    List<XmlNode> attrList;{
        attrList = new ArrayList<>();
    }



    public boolean isLeaf(){
        if (childList.size() == 0 && value == null){
            return true;
        }
        return false;
    }

    public XmlNode findChildByName(String name){
        return childList.stream()
                .filter(xn->xn.getName().equals(name))
                .findFirst()
                .orElse(null);//有就返回xmlNode，没有就返回null
    }

    public XmlNode findAttrByName(String attrName)
    {
        return attrList.stream().filter(xn->{
            return xn.getName().equals(attrName);
        }).findFirst().orElse(null);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public List<XmlNode> getChildList() {
        return childList;
    }

    public void addChild(XmlNode child) {
        this.childList.add(child);
    }

    public void addChild(Collection<XmlNode> childList){
        this.childList.addAll(childList);
    }

    @Override
    public String toString() {
        return "XmlNode{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", attrList='[" + attrList.stream().map(XmlNode::toString).reduce((x,y)->x+y).orElse("") + "]" +
                ", childList=[" + childList.stream().map(XmlNode::toString).reduce((x,y)->x+","+y).orElse("") +"]"+
                '}';
    }


    public List<XmlNode> getAttrList() {
        return attrList;
    }
    public void addAttr(XmlNode attr) {
        this.attrList.add(attr);
    }

    public void addAttr(Collection<XmlNode> attrs){
        this.attrList.addAll(attrs);
    }
}
